package com.zzyy.study.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2025-03-25 22:18
 */
@RestController
public class StreamController {

    @GetMapping(value = "/stream", produces = "text/event-stream;charset=UTF-8")
    public SseEmitter streamData() {
        // 创建 SSE 发射器，设置超时时间（例如 1 分钟）
        SseEmitter emitter = new SseEmitter(60_000L);

        // 创建新线程，防止主程序阻塞
        new Thread(() -> {
            try {
                for (int i = 1; i <= 20; i++) {
                    //暂停1秒钟线程
                    try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
                    // 发送数据
                    emitter.send("时间戳=" + System.currentTimeMillis());
                }
                // 发送完毕
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }
}
